# coding:utf-8
from PySide6.QtCore import QObject, Signal
from serial import Serial
from APP.HYB01Power.ThreadFun.RXHYB01PowerThread import rxHYB01PowerThread
import serial.tools.list_ports
import time

# @pyqtSignal
class SerialHYB01PowerHandle(QObject):
    EventHYB01PowerSignal = Signal(bool)
    HYB01PowerReceiveDataSignal = Signal(list)

    def __init__(self):
        super().__init__()
        self.Ser = Serial()
        self.ComRxThread = None
        self.Ser.port = None
        self.BaudRate = 115200
        self.parity = serial.PARITY_NONE
        self.bytesize = serial.EIGHTBITS
        self.stopbits = serial.STOPBITS_ONE
        self.FirstOpenSerial = True
        self.rxHYB01PowerThread = rxHYB01PowerThread(self)


    def openSerialPort(self, com):
        if not self.Ser.isOpen():
            try:
                # print(u'选择的com为：' + com)
                self.Ser.port = com
                self.Ser.parity = self.parity
                self.Ser.baudrate = self.BaudRate
                # print(self.BaudRate)
                self.Ser.bytesize = self.bytesize
                self.Ser.stopbits = self.stopbits
                self.Ser.open()
            except Exception as e:
                return False
            else:
                if self.FirstOpenSerial:  # 判断线程是否存活
                    self.rxHYB01PowerThread.start()
                    self.FirstOpenSerial = False
                    pass
                else:
                    self.rxHYB01PowerThread.resume()
                    pass
                self.EventHYB01PowerSignal.emit(True)
                return True
        else:
            # print(u'关闭串口')
            self.rxHYB01PowerThread.pause()
            self.Ser.close()
            while self.Ser.isOpen(): pass
            # print(u'串口关闭')
            time.sleep(0.5)
            self.EventHYB01PowerSignal.emit(False)
            return True

    def closeSerialPort(self):
        if self.rxHYB01PowerThread.is_alive:
            self.rxHYB01PowerThread.stop()
            time.sleep(0.05)
        if self.Ser.isOpen():
            self.Ser.close()
        while self.Ser.isOpen(): pass
        time.sleep(0.5)
        self.EventHYB01PowerSignal.emit(False)

    def OnReceiveData(self, message):
        self.HYB01PowerReceiveDataSignal.emit(message)

    def SendFrame(self, TxDataBuffer):
        if self.Ser.isOpen() :
            self.Ser.write(TxDataBuffer)
            pass
        pass

    def SetBaudRate(self,SetValue):
        self.BaudRate = SetValue
        pass
